var colNames = null;
var colModel = null;
var flag = false;
var jqGridFlag = true;
$(function() {
	$.ajax({
		type : "POST",
		url : baseURL + "comapportion/initialization",
		success : function(r) {
			if (r.code === 0) {
				$("#apportionSd").val(r.apportionSd);
				$("#apportionEd").val(r.apportionEd);
				colNames = r.colNames;
				colModel = r.colModel;
				firstLoad();
			} else {
				alert(r.msg);
			}
		}
	});
});
function firstLoad() {
	var apportionSd = $("#apportionSd").val();
	var apportionEd = $("#apportionEd").val();
	$("#jqGrid")
			.jqGrid(
					{
						url : baseURL + 'comapportion/list',
						datatype : "json",
						postData : {
							'apportionSd' : apportionSd,
							'apportionEd' : apportionEd
						},
						colNames : colNames,
						colModel : colModel,
						viewrecords : true,
						height : 385,
						rowNum : 10,
						rowList : [ 10, 30, 50 ],
						rownumbers : true,
						rownumWidth : 25,
						autowidth : true,
						shrinkToFit : false,
						footerrow : true,
						sortable : false,
						multiselect : true,
						pager : "#jqGridPager",
						jsonReader : {
							root : "page.list",
							page : "page.currPage",
							total : "page.totalPage",
							records : "page.totalCount"
						},
						prmNames : {
							page : "page",
							rows : "limit",
							order : "order"
						},
						gridComplete : function() {
							$
									.each(
											$("td[aria-describedby='jqGrid_billNo']"),
											function(i, n) {
												$(n)
														.html(
																"<a href='javascript:;' data-url='"
																		+ baseURL
																		+ "comcollectionrecord/mimeograph?billNo="
																		+ $(n)
																				.text()
																		+ "'>"
																		+ $(n)
																				.text()
																		+ "</a>");
											});
							$("a").click(
									function() {
										var url = $(this).attr("data-url");
										if (url) {
											var num = url.indexOf("?")
											if (num != -1) {
												location.href = $(this).attr(
														"data-url")
														+ "&token=" + token;
											} else {
												location.href = $(this).attr(
														"data-url")
														+ "?token=" + token;
											}
										}
									});
							// jqGrid底部合计
							var rowNum = parseInt($(this).getGridParam(
									"records"), 10);
							if (rowNum > 0) {
								var jz = {};
								$(".ui-jqgrid-sdiv").show();
								for (var i = 13; i < colModel.length; i++) {
									jz[colModel[i].name] = $(this).getCol(
											colModel[i].name, false, "sum")
											.toFixed(2);
								}
								$(this).footerData("set", jz); // 将合计值显示出来
							} else {
								$(".ui-jqgrid-sdiv").hide();
							}
							if (jqGridFlag) {
								// 冻结列
								$("#jqGrid").jqGrid('setFrozenColumns');
								airbus();
								frozenDislocation();
								jqGridFlag = false;
							}
							setTimeout(function() {
								$('.frozen-bdiv.ui-jqgrid-bdiv').height(
										$('.frozen-bdiv.ui-jqgrid-bdiv')
												.height() - 1)
							}, 100);
						}
					});
};
function reLoad() {
	$("#jqGridTable").empty().html(
			'<table id="jqGrid"></table><div id="jqGridPager"></div>');
	var apportionSd = $("#apportionSd").val();
	var apportionEd = $("#apportionEd").val();
	var collectionDaysSd = $("#collectionDaysSd").val();
	var collectionDaysEd = $("#collectionDaysEd").val();
	var items = $(".am-selected-status.am-fl").text();
	$("#jqGrid")
			.jqGrid(
					{
						url : baseURL + 'comapportion/list',
						datatype : "json",
						postData : {
							'apportionSd' : apportionSd,
							'apportionEd' : apportionEd,
							'collectionDaysSd' : collectionDaysSd,
							'collectionDaysEd' : collectionDaysEd,
							'buildIds' : vm.q.buildIds,
							'assetIds' : vm.q.assetIds,
							'contractNo' : vm.q.contractNo,
							'billNo' : vm.q.billNo,
							'renter' : vm.q.renter,
							'items' : items
						},
						colNames : colNames,
						colModel : colModel,
						viewrecords : true,
						height : 385,
						rowNum : 10,
						rowList : [ 10, 30, 50 ],
						rownumbers : true,
						rownumWidth : 25,
						autowidth : true,
						shrinkToFit : false,
						footerrow : true,
						sortable : false,
						footerrow : true,
						multiselect : true,
						pager : "#jqGridPager",
						jsonReader : {
							root : "page.list",
							page : "page.currPage",
							total : "page.totalPage",
							records : "page.totalCount"
						},
						prmNames : {
							page : "page",
							rows : "limit",
							order : "order"
						},
						gridComplete : function() {
							$
									.each(
											$("td[aria-describedby='jqGrid_billNo']"),
											function(i, n) {
												$(n)
														.html(
																"<a href='javascript:;' data-url='"
																		+ baseURL
																		+ "comcollectionrecord/mimeograph?billNo="
																		+ $(n)
																				.text()
																		+ "'>"
																		+ $(n)
																				.text()
																		+ "</a>");
											});
							$("a").click(
									function() {
										var url = $(this).attr("data-url");
										if (url) {
											var num = url.indexOf("?")
											if (num != -1) {
												location.href = $(this).attr(
														"data-url")
														+ "&token=" + token;
											} else {
												location.href = $(this).attr(
														"data-url")
														+ "?token=" + token;
											}
										}
									});
							// jqGrid底部合计
							var rowNum = parseInt($(this).getGridParam(
									"records"), 10);
							if (rowNum > 0) {
								var jz = {};
								$(".ui-jqgrid-sdiv").show();
								for (var i = 13; i < colModel.length; i++) {
									jz[colModel[i].name] = $(this).getCol(
											colModel[i].name, false, "sum")
											.toFixed(2);
								}
								$(this).footerData("set", jz); // 将合计值显示出来
							} else {
								$(".ui-jqgrid-sdiv").hide();
							}
							if (jqGridFlag) {
								// 冻结列
								$("#jqGrid").jqGrid('setFrozenColumns');
								airbus();
								frozenDislocation();
								jqGridFlag = false;
							}
							setTimeout(function() {
								$('.frozen-bdiv.ui-jqgrid-bdiv').height(
										$('.frozen-bdiv.ui-jqgrid-bdiv')
												.height() - 1)
							}, 100);
						}
					});
};
function airbus() {
	$(".ui-jqgrid-sdiv").find("td[aria-describedby='jqGrid_assetIds']").empty()
			.text("合计");
	$(".frozen-sdiv.ui-jqgrid-sdiv").find(
			"td[aria-describedby='jqGrid_billNo']").empty();
};
function frozenDislocation() {
	// 冻结错位解决
	var bdivTop = -1;
	var sdivTop = -1;
	// opera 不需要hack
	if (navigator.userAgent.indexOf("Opera") >= 0) {
		divTop = 0;
		bdivTop = 0;
	}
	$('.frozen-bdiv.ui-jqgrid-bdiv').css({
		top : $('.frozen-bdiv.ui-jqgrid-bdiv').position().top + bdivTop
	});
	$('.frozen-sdiv.ui-jqgrid-sdiv').css({
		top : $('.frozen-sdiv.ui-jqgrid-sdiv').position().top + sdivTop
	});
};
var vm = new Vue(
		{
			el : '#rrapp',
			data : {
				showList : true,
				title : null,
				comCollectionRecord : {},
				q : {}
			},
			methods : {
				exportExcel : function() {
					vm.q.apportionSd = $('#apportionSd').val();
					vm.q.apportionEd = $('#apportionEd').val();
					vm.q.collectionDaysSd = $('#collectionDaysSd').val();
					vm.q.collectionDaysEd = $('#collectionDaysEd').val();
					var url = "comapportion/export?token=" + token;
					if (vm.q.apportionSd) {
						url += "&apportionSd=" + vm.q.apportionSd;
					}
					if (vm.q.apportionEd) {
						url += "&apportionEd=" + vm.q.apportionEd;
					}
					if (vm.q.collectionDaysSd) {
						url += "&collectionDaysSd=" + vm.q.collectionDaysSd;
					}
					if (vm.q.collectionDaysEd) {
						url += "&collectionDaysEd=" + vm.q.collectionDaysEd;
					}
					if (vm.q.buildIds) {
						url += "&buildIds=" + vm.q.buildIds;
					}
					if (vm.q.assetIds) {
						url += "&assetIds=" + vm.q.assetIds;
					}
					if (vm.q.contractNo) {
						url += "&contractNo=" + vm.q.contractNo;
					}
					if (vm.q.billNo) {
						url += "&billNo=" + vm.q.billNo;
					}
					if (vm.q.renter) {
						url += "&renter=" + vm.q.renter;
					}
					url += "&items=" + $(".am-selected-status.am-fl").text();
					location.href = baseURL + url;
				},
				query : function() {
					vm.reload();
				},
				add : function() {
					vm.showList = false;
					vm.title = "新增";
					vm.comCollectionRecord = {};
				},
				update : function() {
					var serialNo = getSelectedRow();
					if (serialNo == null) {
						return;
					}
					vm.showList = false;
					vm.title = "修改";
					vm.getInfo(serialNo);
				},
				saveOrUpdate : function(event) {
					var apportionList = [];
					var allTr = $("#table tr:has(input)");
					for (var i = 0; i < allTr.length; i++) {
						var tr = allTr.eq(i);
						var list = [];
						list.push(tr.find('td').eq(0).find('label').text()
								.trim());
						for (var j = 1; j < tr.find('td').length; j++) {
							list.push(tr.find('td').eq(j).find('input').val());
						}
						apportionList.push(list);
					}
					vm.comCollectionRecord.apportionList = apportionList;
					$.ajax({
						type : "POST",
						url : baseURL + "comapportion/update",
						data : JSON.stringify(vm.comCollectionRecord),
						success : function(r) {
							if (r.code === 0) {
								alert('操作成功', function(index) {
									vm.reload();
								});
							} else {
								alert(r.msg);
							}
						}
					});
				},
				del : function(event) {
					var serialNos = getSelectedRows();
					if (serialNos == null) {
						return;
					}
					confirm('确定要删除选中的记录？', function() {
						$.ajax({
							type : "POST",
							url : baseURL + "comapportion/delete",
							data : JSON.stringify(serialNos),
							success : function(r) {
								if (r.code == 0) {
									alert('操作成功', function(index) {
										$("#jqGrid").trigger("reloadGrid");
									});
								} else {
									alert(r.msg);
								}
							}
						});
					});
				},
				getInfo : function(serialNo) {
					$("#table tr:not(:first)").remove();
					$
							.get(
									baseURL + "comapportion/info/" + serialNo,
									function(r) {
										vm.comCollectionRecord = r.comCollectionRecord;
										var ai = "";
										$
												.each(
														r.comCollectionRecord.apportionList,
														function(i, m) {
															ai += "<tr style='height:50px'>";
															$
																	.each(
																			m,
																			function(
																					j,
																					n) {
																				if (j != 0) {
																					if (j == 1) {
																						ai += "<td style='width:90px'><label style='width:80px;height:40px;display:inline;vertical-align:middle;'>"
																								+ n
																								+ "</label></td>";
																					} else {
																						if ("before" === m[0]) {
																							ai += "<td style='width:90px'><label style='width:80px;height:40;pxpadding-top:14px'>"
																									+ n
																									+ "</label></td>";
																						}
																						if ("after" === m[0]) {
																							ai += "<td style='width:90px'><input type='text' value='"
																									+ n
																									+ "' style='width:80px;height:40px'/></td>";
																						}
																					}
																				}
																			})
															ai += "</tr>";
														})
										$("#table").append(ai);
									});
				},
				reload : function(event) {
					vm.showList = true;
					var apportionSd = $("#apportionSd").val();
					var apportionEd = $("#apportionEd").val();
					if (flag) {
						// 改变jqgrid表头字段
						$.ajax({
							type : "POST",
							url : baseURL
									+ "comapportion/changeJqGrid?apportionSd="
									+ apportionSd + "&apportionEd="
									+ apportionEd,
							success : function(r) {
								if (r.code === 0) {
									colNames = r.colNames;
									colModel = r.colModel;
									jqGridFlag = true;
									reLoad();
								} else {
									alert(r.msg);
								}
							}
						});
						flag = false;
					} else {
						var collectionDaysSd = $("#collectionDaysSd").val();
						var collectionDaysEd = $("#collectionDaysEd").val();
						var items = $(".am-selected-status.am-fl").text();
						var page = $("#jqGrid").jqGrid('getGridParam', 'page');
						$("#jqGrid").jqGrid('setGridParam', {
							postData : {
								'apportionSd' : apportionSd,
								'apportionEd' : apportionEd,
								'collectionDaysSd' : collectionDaysSd,
								'collectionDaysEd' : collectionDaysEd,
								'buildIds' : vm.q.buildIds,
								'assetIds' : vm.q.assetIds,
								'contractNo' : vm.q.contractNo,
								'billNo' : vm.q.billNo,
								'renter' : vm.q.renter,
								'items' : items
							},
							page : page
						}).trigger("reloadGrid");
					}
				},
			}
		});
$('#apportionSd').datepicker().on('changeDate.datepicker.amui',
		function(event) {
			var date = new Date(event.date);
			var year = date.getFullYear();
			var month = date.getMonth() + 1;
			if (month < 10) {
				month = '0' + month;
			}
			$('#apportionSd').val(year + '-' + month);
			flag = true;
		});
$('#apportionEd').datepicker().on('changeDate.datepicker.amui',
		function(event) {
			var date = new Date(event.date);
			var year = date.getFullYear();
			var month = date.getMonth() + 1;
			if (month < 10) {
				month = '0' + month;
			}
			$('#apportionEd').val(year + '-' + month);
			flag = true;
		});